package com.wxzz.elearing.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.pay.dto.ListWxUserActivityDto;
import com.wxzz.elearing.pay.dto.SelectAllOrderStatisticsVoByTypeDto;
import com.wxzz.elearing.pay.dto.UserOrderByCurriculumDto;
import com.wxzz.elearing.pay.dto.UserOrderDto;
import com.wxzz.elearing.pay.entity.UserOrder;
import com.wxzz.elearing.pay.entity.UserOrderStatisticsData;
import com.wxzz.elearing.pay.mapper.PlatformLivetelecastOrderDataMapper;
import com.wxzz.elearing.pay.mapper.UserOrderMapper;
import com.wxzz.elearing.pay.mapper.UserOrderStatisticsDataMapper;
import com.wxzz.elearing.pay.service.IUserOrderService;
import com.wxzz.elearing.pay.vo.*;
import com.wxzz.elearning.common.dto.ActivityStatisticsDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 用户订单表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-23
 */
@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, UserOrder> implements IUserOrderService {

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Override
    public ReturnVO<JgPageVo<UserOrder>> listUserOrder(UserOrderDto userOrderDto) {
        PageHelper.startPage(userOrderDto.getCurPage(), userOrderDto.getMaxPage());
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userOrderDto.getPayName())) {
            queryWrapper.like("pay_name", userOrderDto.getPayName());
        }
        if (userOrderDto.getUserId() != null) {
            queryWrapper.eq("user_id", userOrderDto.getUserId());
        }
        if (userOrderDto.getUserType() != null) {
            queryWrapper.eq("user_type", userOrderDto.getUserType());
        }
        if (userOrderDto.getModelType() != null) {
            queryWrapper.eq("model_type", userOrderDto.getModelType());
        }
        if (StringUtils.isNotBlank(userOrderDto.getOrderNum())) {
            queryWrapper.eq("order_num", userOrderDto.getOrderNum());
        }
        if (userOrderDto.getStartTime() != null && userOrderDto.getEndTime() != null) {
            queryWrapper.between("create_time", userOrderDto.getStartTime(), userOrderDto.getEndTime());
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("order_status", 1);
        List<UserOrder> userOrders = userOrderMapper.selectList(queryWrapper);
        return new ReturnVO<>("订单列表查询成功", new JgPageVo<>(new PageInfo(userOrders)));
    }

    @Override
    public ReturnVO<UserOrder> selectUserOrderById(Long userOrderId) {
        UserOrder userOrder = userOrderMapper.selectById(userOrderId);
        Optional.ofNullable(userOrder).orElseThrow(() -> new ServiceException("该订单不存在"));
        return new ReturnVO<>("订单查询成功", userOrder);
    }

    @Override
    public ReturnVO selectPayStatus(Long userOrderId) {
        UserOrder userOrder = userOrderMapper.selectById(userOrderId);
        return new ReturnVO<>("订单查询成功", userOrder);
    }

    @Override
    public ReturnVO selectUserOrderByCurriculum(UserOrderByCurriculumDto userOrderByCurriculumDto) {
        PageHelper.startPage(userOrderByCurriculumDto.getCurPage(), userOrderByCurriculumDto.getMaxPage());
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("order_status", 1);
        queryWrapper.eq("business_id", userOrderByCurriculumDto.getCurriculumId());
        queryWrapper.eq("model_type", 0);
        List<UserOrder> userOrders = userOrderMapper.selectList(queryWrapper);
        return new ReturnVO<>("销售列表查询成功", new JgPageVo<>(new PageInfo(userOrders)));
    }

    @Override
    public ReturnVO<UserOrderByCurriculumVo> selectUserOrderByCurriculumVo(Long curriculumId) {
        UserOrderByCurriculumVo userOrderByCurriculumVo = new UserOrderByCurriculumVo();
        //个人购买销售额
        BigDecimal salesAmount4person = new BigDecimal("0.00");
        //企业购买销售额
        BigDecimal salesAmount4enterprise = new BigDecimal("0.00");
        List<UserOrder> userOrders = userOrderMapper.selectList(new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getModelType, 0)
                .eq(UserOrder::getBusinessId, curriculumId)
                .eq(UserOrder::getOrderStatus, 1));
        for (UserOrder userOrder : userOrders) {
            //企业管理端
            if (userOrder.getUserType() == 0) {
                salesAmount4enterprise = salesAmount4enterprise.add(userOrder.getIncomePrice());
            }
            //用户端
            if (userOrder.getUserType() == 1) {
                salesAmount4person = salesAmount4person.add(userOrder.getIncomePrice());
            }
        }
        userOrderByCurriculumVo.setSalesAmount4person(salesAmount4person);
        userOrderByCurriculumVo.setSalesAmount4enterprise(salesAmount4enterprise);
        //累计销售金额
        userOrderByCurriculumVo.setAllSalesAmount(salesAmount4person.add(salesAmount4enterprise));
        //累计销售数量
        userOrderByCurriculumVo.setAllSalesQuantity(userOrders.size());
        return new ReturnVO<>("销售情况查询成功", userOrderByCurriculumVo);
    }

    @Autowired
    private PlatformLivetelecastOrderDataMapper platformLivetelecastOrderDataMapper;

    @Override
    public BigDecimal selectCountAmount(Long platformLivetelecastId, Integer onlineType) {
        BigDecimal bigDecimal = platformLivetelecastOrderDataMapper.selectCountAmount(platformLivetelecastId, onlineType);
        if (bigDecimal == null) {
            return new BigDecimal("0.00");
        }
        return bigDecimal;
    }


    @Override
    public List<ActivityStatisticsDto> selectActivityStatisticsDto(Long activityId) {
        return platformLivetelecastOrderDataMapper.selectActivityStatisticsDto(activityId);
    }

    @Override
    public ReturnVO<ActivityStatisticsVo> selectActivityStatisticsVo(Long activityId) {
        List<ActivityStatisticsDto> activityStatisticsDtos = selectActivityStatisticsDto(activityId);
        List<String> saveTime = Lists.newArrayList();
        List<BigDecimal> amount = Lists.newArrayList();
        if (activityStatisticsDtos != null) {
            for (ActivityStatisticsDto activityStatisticsDto : activityStatisticsDtos) {
                saveTime.add(activityStatisticsDto.getSaveTime());
                amount.add(activityStatisticsDto.getAmount());
            }
        }
        ActivityStatisticsVo activityStatisticsVo = new ActivityStatisticsVo();
        activityStatisticsVo.setSaveTime(saveTime);
        activityStatisticsVo.setAmount(amount);
        return new ReturnVO<>("活动销售统计数据查询成功", activityStatisticsVo);
    }

    @Override
    public ReturnVO<JgPageVo<List<UserOrder>>> listUserOrderIdByActivity(ListWxUserActivityDto listWxUserActivityDto) {
        PageHelper.startPage(listWxUserActivityDto.getCurPage(), listWxUserActivityDto.getMaxPage());
        List<UserOrder> userOrders = userOrderMapper.selectList(new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getBusinessId, listWxUserActivityDto.getActivity())
                .eq(UserOrder::getOrderStatus, 1));
        return new ReturnVO<>("活动销售记录查询成功", new JgPageVo<>(new PageInfo(userOrders)));
    }

    @Autowired
    private UserOrderStatisticsDataMapper userOrderStatisticsDataMapper;

    @Override
    public ReturnVO<AllOrderStatisticsVo> selectAllOrderStatisticsVo() {
        AllOrderStatisticsVo allOrderStatisticsVo = new AllOrderStatisticsVo();
        String endTime = LocalDate.now().minusDays(1).toString();
        //今日
        SelectAllIncomePriceVo today = userOrderMapper.selectAllIncomePriceToday(LocalDate.now().toString(), LocalDate.now().plusDays(1).toString());
        if (today != null) {
            allOrderStatisticsVo.setTodayAllOrderPrice(today.getAmount());
            allOrderStatisticsVo.setTodayAllOrderNum(today.getOrderNum());
        }
        //昨日
        SelectAllIncomePriceVo yesterday = userOrderStatisticsDataMapper.selectUserOrderStatisticsDataBySaveTime(endTime, endTime);
        if (yesterday != null) {
            allOrderStatisticsVo.setYesterdayAllOrderPrice(yesterday.getAmount());
            allOrderStatisticsVo.setYesterdayAllOrderNum(yesterday.getOrderNum());
        }
        //近30天
        SelectAllIncomePriceVo month = userOrderStatisticsDataMapper.selectUserOrderStatisticsDataBySaveTime(LocalDate.now().minusDays(30).toString(), endTime);
        if (month != null) {
            allOrderStatisticsVo.setMonthAllOrderPrice(month.getAmount().add(today.getAmount()));
            allOrderStatisticsVo.setMonthAllOrderNum(month.getOrderNum() + today.getOrderNum());
        }
        //累计
        SelectAllIncomePriceVo selectAllIncomePriceVo = userOrderStatisticsDataMapper.selectAllUserOrderStatisticsData();
        if (selectAllIncomePriceVo != null) {
            allOrderStatisticsVo.setAllOrderPrice(selectAllIncomePriceVo.getAmount().add(today.getAmount()));
            allOrderStatisticsVo.setAllOrderNum(selectAllIncomePriceVo.getOrderNum() + today.getOrderNum());
        }

        return new ReturnVO<>("概况总览查询成功", allOrderStatisticsVo);
    }

    @Override
    public ReturnVO<AllOrderStatisticsTypeVo> selectAllOrderStatisticsVoByType(SelectAllOrderStatisticsVoByTypeDto selectAllOrderStatisticsVoByTypeDto) {
        AllOrderStatisticsTypeVo allOrderStatisticsTypeVo = new AllOrderStatisticsTypeVo();
        List<UserOrderStatisticsData> allCourse = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 0)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        //时间
        List<String> saveTimeList = Lists.newArrayList();
        //课程收入
        List<BigDecimal> allCourseList = Lists.newArrayList();
        for (UserOrderStatisticsData userOrderStatisticsDatum : allCourse) {
            allCourseList.add(userOrderStatisticsDatum.getAmount());
            saveTimeList.add(userOrderStatisticsDatum.getSaveTime());
        }
        allOrderStatisticsTypeVo.setSaveTimeList(saveTimeList);
        allOrderStatisticsTypeVo.setAllCourseList(allCourseList);
        //直播收入
        List<BigDecimal> allLiveList = Lists.newArrayList();
        List<UserOrderStatisticsData> allLive = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 1)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        for (UserOrderStatisticsData userOrderStatisticsData : allLive) {
            allLiveList.add(userOrderStatisticsData.getAmount());
        }
        allOrderStatisticsTypeVo.setAllLiveList(allLiveList);
        //线上活动收入
        List<BigDecimal> allOnActivityList = Lists.newArrayList();
        List<UserOrderStatisticsData> allOnActivity = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 2)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        for (UserOrderStatisticsData userOrderStatisticsData : allOnActivity) {
            allOnActivityList.add(userOrderStatisticsData.getAmount());
        }
        allOrderStatisticsTypeVo.setAllOnActivityList(allOnActivityList);
        //问答打赏收入
        List<BigDecimal> allAnswersList = Lists.newArrayList();
        List<UserOrderStatisticsData> allAnswers = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 3)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        for (UserOrderStatisticsData userOrderStatisticsData : allAnswers) {
            allAnswersList.add(userOrderStatisticsData.getAmount());
        }
        allOrderStatisticsTypeVo.setAllAnswersList(allAnswersList);
        //直播打赏收入
        List<BigDecimal> allRewardList = Lists.newArrayList();
        List<UserOrderStatisticsData> allReward = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 4)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        for (UserOrderStatisticsData userOrderStatisticsData : allReward) {
            allRewardList.add(userOrderStatisticsData.getAmount());
        }
        allOrderStatisticsTypeVo.setAllRewardList(allRewardList);
        //线下活动收入
        List<BigDecimal> allOffActivityList = Lists.newArrayList();
        List<UserOrderStatisticsData> allOffActivity = userOrderStatisticsDataMapper.selectList(new LambdaQueryWrapper<UserOrderStatisticsData>()
                .eq(UserOrderStatisticsData::getModelType, 5)
                .between(UserOrderStatisticsData::getSaveTime, selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime())
                .orderByAsc(UserOrderStatisticsData::getSaveTime));
        for (UserOrderStatisticsData userOrderStatisticsData : allOffActivity) {
            allOffActivityList.add(userOrderStatisticsData.getAmount());
        }
        allOrderStatisticsTypeVo.setAllOffActivityList(allOffActivityList);
        //总收入
        List<BigDecimal> allList = Lists.newArrayList();
        List<BigDecimal> bigDecimals = userOrderStatisticsDataMapper.selectListAmount(selectAllOrderStatisticsVoByTypeDto.getStartTime(), selectAllOrderStatisticsVoByTypeDto.getEndTime());
        for (BigDecimal bigDecimal : bigDecimals) {
            allList.add(bigDecimal);
        }
        allOrderStatisticsTypeVo.setAllList(allList);
        return new ReturnVO<>("概况总览查询成功", allOrderStatisticsTypeVo);
    }
}
